package org.jeecg.modules.system.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

public class RequestLoggerInterceptor implements HandlerInterceptor {
    public static final String REQUEST_ID = "requestId";
    public static final String REQUEST_URL = "requestUrl";
    public static final String REQUEST_METHOD = "requestMethod";

    public RequestLoggerInterceptor() {
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (StringUtils.isBlank(MDC.get("requestId"))) {
            MDC.put("requestId", String.valueOf(System.currentTimeMillis()));
        }

        if (StringUtils.isBlank(MDC.get("requestUrl"))) {
            MDC.put("requestUrl", request.getRequestURI());
        }

        if (StringUtils.isBlank(MDC.get("requestMethod"))) {
            MDC.put("requestMethod", request.getMethod().toLowerCase());
        }

        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove("requestId");
        MDC.remove("requestUrl");
        MDC.remove("requestMethod");
    }
}